/*******************************************************************************
 * Copyright (c) 2017-2022, org.smartboot. All rights reserved.
 * project name: smart-http
 * file name: LfDecoder.java
 * Date: 2022-01-12
 * Author: sandao (zhengjunweimail@163.com)
 ******************************************************************************/

package org.smartboot.http.server.decode;

import org.smartboot.http.common.enums.HttpStatus;
import org.smartboot.http.common.exception.HttpException;
import org.smartboot.http.common.utils.Constant;
import org.smartboot.http.server.HttpServerConfiguration;
import org.smartboot.http.server.impl.Request;

import java.nio.ByteBuffer;

/**
 * @author 三刀（zhengjunweimail@163.com）
 * @version V1.0 , 2022/1/12
 */
//检查http请求行中的换行符
class LfDecoder extends AbstractDecoder {

    //用于存储下一个解码器
    private final AbstractDecoder nextDecoder;


    public LfDecoder(AbstractDecoder nextDecoder, HttpServerConfiguration configuration) {
        super(configuration);
        this.nextDecoder = nextDecoder;
    }

    @Override
    public Decoder decode0(ByteBuffer byteBuffer, Request request) {
        if (byteBuffer.hasRemaining()) {   //检查byteBuffer是否有剩余字节
            if (byteBuffer.get() != Constant.LF) {    //byteBuffer中的下一个字节不是换行符
                //抛出异常表示请求格式不正确
                throw new HttpException(HttpStatus.BAD_REQUEST);
            }
            return nextDecoder.decode(byteBuffer, request);
        }
        //如果没有下一个字节了返回当前解码器
        return this;
    }
}
